package org.xenon.vote.dao.imp;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.xenon.vote.dao.StringDao;
import org.xenon.vote.model.pojo.po.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDao implements StringDao<User> {

    private final JdbcTemplate jdbcTemplate;

    public UserDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }


    @Override
    public void add(User user) {
        String sql = "insert into `vote`.`user` (`name`, `password`, `mail`, `group`) values (?, ?, ?, ?)";
        jdbcTemplate.update(sql, user.getName(), user.getPassword(), user.getMail(), user.getGroup());
    }

    @Override
    public void edit(User user) {
        String sql = "update `vote`.`user` set `name` = ? , `password` = ? , `mail` = ? , `group` = ? where `mail` = ?";
        jdbcTemplate.update(sql, user.getName(), user.getPassword(), user.getMail(), user.getGroup(), user.getMail());
    }

    @Override
    public User get(String mail){
        String sql = "select * from `vote`.`user` where `mail` = ?";
        List<User> list = jdbcTemplate.query(sql, new Object[]{mail}, UserRowMapper.getInstance());
        if (list.size() == 0) return null;
        return list.get(0);
    }

    /**
     * 查询所有名字是某个值的人
     */
    @Override
    public List<User> getAll(String name) {
        String sql = "select * from `vote`.`user` where `name` = ?";
        return jdbcTemplate.query(sql, new Object[]{name}, UserRowMapper.getInstance());
    }

    @Override
    public void del(User user) {
        String sql = "delete FROM `vote`.`user` WHERE `mail` = ?";
        jdbcTemplate.update(sql, user.getMail());
    }

    @Override
    public void del(String mail){
        String sql = "delete FROM `vote`.`user` WHERE `mail` = ?";
        jdbcTemplate.update(sql, mail);
    }

    /**
     * 自动以RowMapper
     * 提高性能, 使用单例模式
     */
    private static class UserRowMapper implements RowMapper<User> {

        private static UserRowMapper userRowMapper;
        @Override
        public User mapRow(ResultSet rs, int i) throws SQLException {
            return new User(rs.getString("name"),
                    rs.getString("password"),
                    rs.getString("mail"),
                    rs.getString("group"));
        }

        static UserRowMapper getInstance(){
            if (userRowMapper == null){
                synchronized (UserRowMapper.class){
                    if(userRowMapper==null){
                        userRowMapper = new UserRowMapper();
                    }
                }
            }
            return userRowMapper;
        }
    }
}
